package cn.assumejson.pro_netty.spring;

import cn.assumejson.pro_netty.annotation.Remote;
import cn.assumejson.pro_netty.core.Mediator;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 容器在初始化后，获取所有使用{@link cn.assumejson.pro_netty.annotation.Remote}的方法
 * 并且存入到缓存中
 * 并且需要保证该方法 在Netty服务之前完成{@link NettyApplicationListener}
 *
 * @author by gang.Li 2022/3/12 14:45
 */
@Component
public class InitLoadRemoteMethod implements ApplicationListener<ContextRefreshedEvent>, Ordered {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 获取容器中所有使用Controller的Bean
        Map<String, Object> controllerBeans =
                contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(Remote.class);

        controllerBeans.keySet().forEach(s -> {
            Object bean = controllerBeans.get(s);
            // 通过反射获取到所有的@Controller的所有方法
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                String methodVal = bean.getClass().getInterfaces()[0].getName() + "." + method.getName();
                // 存入缓存
                Mediator.MethodBean methodBean = new Mediator.MethodBean();
                methodBean.setBean(bean);
                methodBean.setMethod(method);

                Mediator.methodBeans.put(methodVal, methodBean);


            }

        });
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
